import os
from flask import Flask, request, render_template
import fun

print('create.py 创建FLASK APP对象')

def create_app(config_filename):
    app = Flask('my_app', template_folder='templates', static_folder='static')
    app.config['UPLOAD_FOLDER'] = os.getcwd()+"\\upload\\"
    app.config.from_pyfile(config_filename+'.py', silent=True)  # 导入配置文件
    # print(app.config)
    app.jinja_env.auto_reload = True  # 模板修改后立即生效，无需重启
    @app.route('/test')
    def about():
        print('test')
        return 'test'


    print('注册蓝图')
    from application.admin import admin_blueprint  # 导入admin包的父级蓝图
    from application.api import api_blueprint      # 导入api包的父级蓝图
    from application.index import index_blueprint  # 导入index包的父级蓝图

    app.register_blueprint(admin_blueprint)
    app.register_blueprint(api_blueprint)
    app.register_blueprint(index_blueprint)

    app.add_url_rule('/', endpoint='index.index.index')
    #自定义路由 / 由index.index中.index方法来执行   父蓝图.子蓝图.函数

    #导入fun下的自定义函数 （可以进一步增加前缀来设置绑定条件）
    custom_functions_list = fun.get_custom_functions()
    for v in custom_functions_list:
        app.add_template_filter(getattr(fun, v), v)  # 注册模板过滤器
        app.add_template_global(getattr(fun, v), v)  # 注册模板全局函数


    @app.errorhandler(404)
    def page_not_found(e):
        print('404')
        print(e)
        return render_template('404.html')

    @app.before_request
    def before_request():
        endpoint = request.endpoint #当前运行的蓝图
        path=request.path
        if path in app.route_list:
            print('app===before_request======>')
            print("path:%s" % path)
            print("endpoint:%s" % endpoint)

    #将路由列表转成列表
    route_list = [rule.rule for rule in app.url_map.iter_rules()]
    app.route_list=route_list

    #直接打印路由列表
    # for rule in app.url_map.iter_rules():
    #     print(rule)

    return  app